// 函数组件
import React, { useState, useEffect } from 'react';
import { Button, Modal, Form, Input, Switch, InputNumber, message } from 'antd';
import "../css/SearchDialog.less"
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import { addSearch, modSearch } from '../../../../api/operationApi';

// 表格泛型
interface PropsType {
    isModalOpen: boolean
    modStuInfo?: DataType | undefined
    type: string
    currentPage: number
    pageSize: number
    close(): void
    getData(currentPage: number, pageSize: number): void
    upTotal: number
    data: DataType[]
}

// 数据类型
interface DataType {
    searchId: number,
    searchName: string,
    searchState: number,
    searchLocation: number,
}

// 表单布局
const layout = {
    labelCol: {
        span: 6,
    },
    wrapperCol: {
        span: 16,
    },
};

// 表单验证
const validateMessages = {
    required: '${label}必填',
    types: {
        number: '${label}必须是数值',
    }
};

function SearchDialog(props: PropsType) {
    const [form] = Form.useForm();
    const [title, setTitle] = useState<string>('')

    useEffect(() => {
        console.log('props',props);
        if (props.type == 'add') {
            setTitle('添加关键词')
            form.resetFields()
            form.setFieldsValue({
                searchId: '',
                searchName: '',
                searchState: false,
                searchLocation: null
            })

        } else if (props.type == 'mod') {
            setTitle('编辑关键词')
            //设置字段默认值
            form.setFieldsValue({
                searchId: props.modStuInfo?.searchId,
                searchName: props.modStuInfo?.searchName,
                searchState: props.modStuInfo?.searchState == 0 ? false : true,
                searchLocation: props.modStuInfo?.searchLocation
            })
        }
    }, [props])


    // 2、点击提交
    const onFinish = async (values: any) => {
        if (props.type === 'add') {
            // 遍历是否有相同的关键词
            let isExist: boolean = false
            try {
                props.data.forEach((item: DataType) => {
                    if (item.searchName == values.searchName) {
                        isExist = true
                        throw ('已存在该关键词')
                    }
                })
            } catch (error) {
                console.log('error', error);
            }

            if (isExist) {
                message.warning('已存在该关键词')
            } else {
                let res = await addSearch({
                    "searchLocation": values.searchLocation,
                    "searchName": values.searchName,
                    "searchState": values.searchState ? 1 : 0
                })
                await props.getData(props.currentPage, props.pageSize)
                message.success('增加成功')
                props.close()
            }
        } else if (props.type === 'mod') {
            let isExist: boolean = false
            try {
                props.data.forEach((item: DataType) => {
                    if (item.searchName == values.searchName && item.searchId!=props.modStuInfo?.searchId) {
                        isExist = true
                        throw ('已存在该关键词')
                    }
                })
            } catch (error) {
                console.log('error', error);
            }

            if (isExist) {
                message.warning('已存在该关键词')
            } else {
                let res = await modSearch({
                    "searchId": values.searchId,
                    "searchLocation": values.searchLocation,
                    "searchName": values.searchName,
                    "searchState": values.searchState ? 1 : 0
                })

                await props.getData(props.currentPage, props.pageSize)
                message.success('修改成功')
                props.close()
            }
        }

    };

    // 点击表单取消
    const cancel = () => {
        message.warning('取消操作')
        props.close()
    }

    // 点击叉叉取消
    const handleCancel = () => {
        message.warning('取消操作')
        props.close()
    };


    // 开关改变
    const onChange = (checked: boolean) => {
        if (checked) {
            if (props.upTotal >= 6 && props.type == 'add') {
                message.warning('最多同时上架六个关键字')
                form.setFieldsValue({
                    searchState: false,
                })
            } else if (props.type === 'mod' && props.modStuInfo?.searchState == 0 && props.upTotal >= 6) {
                message.warning('最多同时上架六个关键字')
                form.setFieldsValue({
                    searchState: false,
                })
            }
        }
    };

    return (
        <div className='Dialog'>
            <Modal centered={true} forceRender width={560} title={title} open={props.isModalOpen} footer={null} onCancel={handleCancel} >
                <Form
                    {...layout}
                    name="search-form"
                    onFinish={onFinish}
                    validateMessages={validateMessages}
                    form={form}
                >
                    {
                        props.type == 'mod' ? (
                            <Form.Item
                                name='searchId'
                                label="序号"
                                rules={[
                                    {
                                        required: true,
                                    },
                                ]}
                                initialValue={props.modStuInfo?.searchId}
                            >
                                <Input disabled />
                            </Form.Item>
                        ) : ''
                    }
                    <Form.Item
                        name='searchName'
                        label="关键词名称"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                        initialValue={props.modStuInfo?.searchName}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        name='searchLocation'
                        label="位置"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                        initialValue={props.modStuInfo?.searchLocation}
                    >
                        <InputNumber placeholder='位置' min={1} max={10}></InputNumber>
                    </Form.Item>



                    <Form.Item
                        name='searchState'
                        label="上架"
                        valuePropName='checked'
                        initialValue={props.modStuInfo?.searchState}
                    >
                        <Switch onChange={onChange} />
                    </Form.Item>


                    <Form.Item
                        wrapperCol={{
                            ...layout.wrapperCol,
                            offset: 8,
                        }}
                    >
                        <Button type="primary" htmlType="submit" className='confirm-btn' >确定</Button>
                        <Button type="primary" onClick={cancel} ghost>取消</Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}

export default SearchDialog